package com.simple.configuration.thymeleaf;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import com.simple.utils.SpringUtils;
import com.simple.utils.SysConfig;

/**
 * thymeleaf 标签处理
 */
public class SysProcessor extends AbstractElementTagProcessor {
	
	private static final Logger logger = LoggerFactory.getLogger(SysProcessor.class);
	
    private static final String ATTRIBUTE_NAME="eachs";
    private static final int PRECEDENCE = 1000;

    public SysProcessor(String dialectPrefix) {

        super(
                TemplateMode.HTML,//模板模式
                dialectPrefix,//标签前缀
                ATTRIBUTE_NAME, //自定义标签属性名
                true,  //属性名是否需要加前缀，比如th:text  th
                null, //匹配标签元素名（限制在哪个表标签下使用，设置为null 都可以）
                false,  //标签名是否需要前缀
                PRECEDENCE); //标签处理之后是否移除属性
    }

    @SuppressWarnings("static-access")
    @Override
    protected void doProcess(ITemplateContext context, IProcessableElementTag tag,
                             IElementTagStructureHandler structureHandler) {

        SysConfig sysConfig= SpringUtils.getBean(SysConfig.class);
        IModelFactory modelFactory = context.getModelFactory();
        final IModel model = modelFactory.createModel();
        StringBuffer element=new StringBuffer();
        if(StringUtils.isNotBlank(sysConfig.getMenuCache())) {//查询缓存
        	logger.info("-->从缓存中读取栏目");
            element=new StringBuffer(sysConfig.getMenuCache());
        }else {
            element=sysConfig.getSysMenu();
        }
        logger.info(""+element);
        model.add(modelFactory.createText(element));
        //指定模型替换整个元素
        structureHandler.replaceWith(model, false);
    }
}
